#ifndef __TCPCONNECTION_H__
#define __TCPCONNECTION_H__

#include "Acceptor.hpp"
#include "Socket.hpp"
#include "SocketIO.hpp"
#include "InetAddress.hpp"

#include <memory>
#include <functional>

using std::shared_ptr;
using std::function;

namespace wd
{

class TcpConnection;
using TcpConnectionPtr      = shared_ptr<TcpConnection>;
using TcpConnectionCallback = function<void(TcpConnectionPtr)>;

class TcpConnection
// 辅助类，为了在成员函数内部通过 this 直接获取本对象的智能指针 shared_ptr
: public std::enable_shared_from_this<TcpConnection>
{
public:
    TcpConnection(int fd);
    
    ~TcpConnection();

    // TcpConnection 内部的 setAllCallbacks 函数不能采用移动语义
    // 必须要表达值语义，不能把 EventLoop 对象的三个函数对象
    // 直接转移到 TcpConnection 对象中，因为 TcpConnection 对象不止一个
    void setAllCallbacks(
                         const TcpConnectionCallback & cb1 , 
                         const TcpConnectionCallback & cb2 , 
                         const TcpConnectionCallback & cb3
                        )
    {
        _onConnection = cb1;
        _onMessage    = cb2;
        _onClose      = cb3;
    }

    string recieve();
    
    void send(const string & msg);

    bool isClosed() const;
    
    void shutdown();
    
    string toString() const;

    void handleNewConnectionCallback();
    
    void handleMessageCallback();
    
    void handleCloseCallback();

private:
    InetAddress getLocalAddress();
    
    InetAddress getPeerAddress();

private:
    Socket      _sock;
    SocketIO    _sockIO;
    InetAddress _localAddr;
    InetAddress _peerAddr;

    TcpConnectionCallback _onConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
};

} // end of namespace wd



#endif

